class UsersController < ApplicationController
  # Be sure to include AuthenticationSystem in Application Controller instead
  #include AuthenticatedSystem
  
  # Protect these actions behind an admin login
  # before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge]
  before_filter :find_user, :only => [:suspend, :unsuspend, :destroy, :purge]
  before_filter :login_required, :only => [:change_password]

  # render new.rhtml
  def new
  end
  
  # GET /users
  # GET /users.xml
  def index
    @users = User.all

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @users }
    end
  end

  def create
    cookies.delete :auth_token
    # protects against session fixation attacks, wreaks havoc with 
    # request forgery protection.
    # uncomment at your own risk
    # reset_session
    #@user = User.new(params[:user])
    #@user.register! if @user.valid?
    
    @user = User.find_or_create_by_email(params[:user])
    if @user.new_record?
      @user.password_confirmation = @user.password
      @user.register!
      self.current_user = @user
      @user.save(:validate => false)
      flash[:notice] = "An activation email has been send to your email address, please follow the activation link."
      redirect_to "#{ActionController::Base.relative_url_root}/"
    else
      flash[:notice] = "This user allready exists."
      render :action => 'new'
      redirect_to "#{ActionController::Base.relative_url_root}/users/new"
    end
  end
  
  def random_password( len = 20 )
    chars = (("a".."z").to_a + ("1".."9").to_a )- %w(i o 0 1 l 0)
    newpass = Array.new(len, '').collect{chars[rand(chars.size)]}.join
  end
  
  # GET /users/1
  # GET /users/1.xml
  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.xml  { render :xml => @user }
    end
  end
  
  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  def activate
    self.current_user = params[:activation_code].blank? ? false : User.find_by_activation_code(params[:activation_code])
    if logged_in? && !current_user.active?
      current_user.activate!
      flash[:notice] = "Signup complete! You can get started by creating a tag."
    end
    redirect_to "#{ActionController::Base.relative_url_root}/"
  end
  
  #
  # Change user passowrd
  def change_password

  end
  
  #
  # Change user passowrd
  def change_password_update
      if User.authenticate(current_user.login, params[:old_password])
          if ((params[:password] == params[:password_confirmation]) && !params[:password_confirmation].blank?)
              current_user.password_confirmation = params[:password_confirmation]
              current_user.password = params[:password]
              
              if current_user.save!
                  flash[:notice] = "Password successfully updated"
                  redirect_to change_password_path
              else
                  flash[:alert] = "Password not changed"
                  render :action => 'change_password'
              end
               
          else
              flash[:alert] = "New Password mismatch" 
              render :action => 'change_password'
          end
      else
          flash[:alert] = "Old password incorrect" 
          render :action => 'change_password'
      end
  end
  
  def forgot
    if request.post?
      user = User.find_by_email(params[:user][:email])
      
      respond_to do |format|
        if user
          user.create_reset_code
          flash[:notice] = "Reset code sent to #{user.email}"
          
          format.html { redirect_to login_path }
          format.xml { render :xml => user.email, :status => :created }
        else
          flash[:error] = "#{params[:user][:email]} does not exist in system"
          
          format.html { redirect_to login_path }
          format.xml { render :xml => user.email, :status => :unprocessable_entity }
        end
      end
      
    end
  end
  
  def reset
    @user = User.find_by_reset_code(params[:reset_code]) unless params[:reset_code].nil?
    if request.post?
      if @user.update_attributes(:password => params[:user][:password], :password_confirmation => params[:user][:password_confirmation])
        self.current_user = @user
        @user.delete_reset_code
        flash[:notice] = "Password reset successfully for #{@user.email}"
        redirect_to "#{ActionController::Base.relative_url_root}/"

      else
        render :action => :reset
      end
    end
  end

  def suspend
    @user.suspend! 
    redirect_to users_path
  end

  def unsuspend
    @user.unsuspend! 
    redirect_to users_path
  end

  def destroy
    @user.delete!
    redirect_to users_path
  end

  def purge
    @user.destroy
    redirect_to users_path
  end

protected
  def find_user
    @user = User.find(params[:id])
  end

end
